package com.cr.admin.base.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.SaTokenException;
import com.cr.common.exception.ServiceException;
import com.cr.common.response.JsonResult;
import com.cr.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import springfox.documentation.spring.web.json.Json;

import javax.validation.ValidationException;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * Sa-Token异常处理
     *
     * @param e Sa-Token异常对象
     * @return {@link JsonResult}
     *
     */
    @ExceptionHandler({SaTokenException.class})
    public JsonResult handlerSaTokenException(SaTokenException e) {
        String msg = e.getMessage();
        log.debug("发生Sa-Token异常:{}",msg);
        if(e instanceof NotLoginException) {
            return JsonResult.error(StatusCode.UNAUTHORIZED,msg);
        }
        return JsonResult.error(StatusCode.FORBIDDEN,msg);
    }

    /**
     * 业务异常处理
     *
     * @param e 业务异常对象
     * @return {@link JsonResult}
     */
    @ExceptionHandler({ServiceException.class})
    public JsonResult handleServiceException(ServiceException e) {
        String msg = e.getMessage();
        log.error("发生业务异常: {}", msg);
        if (e.getCode() != null) {
            return JsonResult.error(e.getCode(), msg);
        }
        return JsonResult.error(msg);
    }

    /**
     * 验证异常处理
     *
     * @param e 验证异常对象
     * @return {@link JsonResult}
     */
    @ExceptionHandler({BindException.class})
    public JsonResult handleBindException(BindException e) {
        //StringBuilder builder = new StringBuilder();
        //e.getFieldErrors().forEach(fieldError -> builder.append(fieldError.getDefaultMessage()).append("<br>"));
        String msg = e.getFieldError().getDefaultMessage();
        log.error("发生验证异常: {}", msg);
        return JsonResult.error(msg);
    }

    /**
     * 验证异常处理
     *
     * @param e 验证异常对象
     * @return {@link JsonResult}
     */
    @ExceptionHandler({ValidationException.class})
    public JsonResult handleValidationException(ValidationException e) {
        String msg = e.getMessage().split(":")[1].trim();
        log.error("发生验证异常: {}", msg);
        return JsonResult.error(msg);
    }

    /**
     * 系统异常处理
     *
     * @param e 系统异常对象
     * @return {@link JsonResult}
     */
    @ExceptionHandler({Throwable.class})
    public JsonResult handleThrowable(Throwable e) {
        log.error("发生系统异常", e);
        return JsonResult.error("服务器忙，请稍后再重试");
    }

}
